from django.contrib.auth.backends import BaseBackend, ModelBackend
import re

from users.models import User


def get_user_by_account(account):
    """
    根据用户名或手机号查找用户
    :param account:  用户名或手机号
    :return: 用户
    """
    try:
        if re.match(r'^1[3-9]\d{9}$', account):
            user = User.objects.get(mobile=account)  # 手机号
        else:
            user = User.objects.get(username=account)  # 用户名
    except User.DoesNotExist:
        return None
    else:
        return user


class UsernameMobileBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        user = get_user_by_account(username)
        if user and user.check_password(password):
            return user
        else:
            return None
